<template>
  <div class="pager-container">
    <a
      :class="{
        disabled: current === 1,
      }"
      @click.prevent="handleClick(1)"
      >首页</a
    >
    <a
      :class="{
        disabled: current === 1,
      }"
      @click.prevent="handleClick(current - 1)"
      >上一页</a
    >
    <a
      :class="{
        active: current === page,
      }"
      v-for="(page, i) in visiblePageList"
      :key="i"
      @click.prevent="handleClick(page)"
      >{{ page }}</a
    >
    <a
      :class="{
        disabled: current === pageNumber,
      }"
      @click.prevent="handleClick(current + 1)"
      >下一页</a
    >
    <a
      :class="{
        disabled: current === pageNumber,
      }"
      @click.prevent="handleClick(pageNumber)"
      >尾页</a
    >
  </div>
</template>

<script>
export default {
  props: {
    current: {
      type: Number,
      default: 1,
    },
    total: {
      type: Number,
      default: 0,
    },
    limit: {
      type: Number,
      default: 10,
    },
    visibleNumber: {
      type: Number,
      default: 10,
    },
  },
  computed: {
    pageNumber() {
      return Math.ceil(this.total / this.limit);
    },
    visiblePageList() {
      let min = Math.floor(this.current - this.visibleNumber / 2);
      if (min < 0) {
        min = 1;
      }
      let max = min + this.visibleNumber - 1;
      if (max > this.pageNumber) {
        max = this.pageNumber;
      }
      const pageList = [];
      for (let i = min; i <= max; i++) {
        pageList.push(i);
      }
      return pageList;
    },
  },
  methods: {
    handleClick(newPage) {
      if (
        newPage < 1 ||
        newPage > this.pageNumber ||
        newPage === this.current
      ) {
        return;
      }
      this.$emit("pageChange", newPage);
    },
  },
};
</script>

<style scoped lang="less">
@import "../styles/color.less";

.pager-container {
  width: 100%;
  text-align: center;
  color: @primary;
  user-select: none;
  margin: 10px 0;
  a {
    cursor: pointer;
    margin: 0 10px;
    &.disabled {
      cursor: not-allowed;
      color: @gray;
    }
    &.active {
      cursor: default;
      color: @words;
      font-weight: bold;
    }
  }
}
</style>